#!/bin/bash

# 该脚本放在工程目录下
WorkSpaceDir=$(dirname $(readlink -f "$0"))
cd $WorkSpaceDir
if [ $? -ne 0 ]; then
    echo "Cd Workspace Dir ($WorkSpaceDir) Fail."
    exit 1
fi

source ./PackageList.sh

function BuildPack()
{
    Pack_Tgt_Map=($1)
    if [ ${#Pack_Tgt_Map[@]} -lt 1 ] ; then
        EchoInfo "BuildPack Null Input !!!!"
        return 0
    fi
    
    Pack=${Pack_Tgt_Map[0]}
    EchoInfo "Begin To Build Package < $Pack > ."
    
    # Del Build And Tgt File
    IsProcPackName=0
    for i in "${Pack_Tgt_Map[@]}" ; do
        if [ $IsProcPackName -eq 0 ] ; then
            IsProcPackName=1
            BuildDir="./build/$i"
            rm -rf "$BuildDir"
            EchoInfo "Del Build Dir: $BuildDir"
        else
            TgtFile="./devel/lib/$i"
            rm -rf "$TgtFile"
            EchoInfo "Del Tgt File: $TgtFile"
        fi
    done
    
    # check
    if [ ! -d "./src/$Pack" ] ; then
        EchoInfo "Pack< $Pack > Not Exist !!!!"
        return 0
    fi
    
    # Build
    Pack=${Pack_Tgt_Map[0]}
    catkin_make -DCATKIN_WHITELIST_PACKAGES=$Pack
    
    # Check Tgt
    IsProcPackName=0
    for i in "${Pack_Tgt_Map[@]}" ; do
        if [ $IsProcPackName -eq 0 ] ; then
            IsProcPackName=1
            continue
        fi
        
        Tgt="$i"
        TgtFile="./devel/lib/$Tgt"
        if [ ! -f "$TgtFile" ] ; then
            EchoInfo "Pack< $Pack > Tgt< $Tgt > File Not Exist !!!!"
            return 0
        fi
    done
    
    EchoInfo "Build Package < $Pack > Succ."
    return 1
}

function BuildPackLst()
{
    Build_Pack_List=($1)
    for Pack in "${Build_Pack_List[@]}" ; do
        BuildPackInfo=$(GetBuildPackInfo "$Pack")
        if [ "$BuildPackInfo" = "" ] ; then
            EchoInfo "$Pack Pack Not Exist!!!!"
            return 0
        fi
        
        
        BuildPack "$BuildPackInfo"
        if [ $? -eq 0 ] ; then
            return 0
        fi
    done
    
    EchoPackList "Build All Package Succ !!!" "${Build_Pack_List[*]}"
    return 1
}

function EchoTimeLen()
{
    Start_Build_Time=$1
    Start_Build_Time_Sec=$(date --date="$Start_Build_Time" +%s);
    
    End_Build_Time=$2
    End_Build_Time_Sec=$(date --date="$End_Build_Time" +%s);
    
    Build_Time_Len=$((End_Build_Time_Sec-Start_Build_Time_Sec))
    Build_Time_Len_H=$((Build_Time_Len/3600))
    Build_Time_Len_M=$(((Build_Time_Len-Build_Time_Len_H*3600)/60))
    Build_Time_Len_S=$(( Build_Time_Len-Build_Time_Len_H*3600-Build_Time_Len_M*60))
    
    EchoInfo "编译总时长： "${Build_Time_Len_H}"小时"${Build_Time_Len_M}"分"${Build_Time_Len_S}"秒 ("${Build_Time_Len}"秒)"
}

EchoInfo ""
EchoInfo ""

if [ "$1" = "" ] ; then
    echo "Please Input Pack List After Cmd!!!!!"
    exit
fi

EchoPackList "Pack List :" "$1"

# 记录开始编译时间
Start_Build_Time=`date +'%Y-%m-%d %H:%M:%S'`

# 开始编译
BuildPackLst "$1"

# 输出编译花费时间
End_Build_Time=`date +'%Y-%m-%d %H:%M:%S'`
EchoTimeLen "$Start_Build_Time" "$End_Build_Time"
